package com.mtf.redis.controller;

import cn.hutool.core.util.ObjectUtil;
import com.mtf.config.JedisPoolManager;
import com.mtf.entity.MtfOrder;
import com.mtf.redis.subscribe.RedisSubscriber;
import com.mtf.service.IMtfOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @Author matengfei
 * @Date 2024/7/1 18:14
 * @PackageName:com.mtf.redis.controller
 * @ClassName: RedisDelayQueueController
 * @Description: 基于Redis的zset实现延时队列
 * @Version 1.0
 */
@RequestMapping("/redisDelayQueue")
@RestController
@Slf4j
public class RedisDelayQueueController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private RedisTemplate<String,Object> jedisTemplate;
    @Autowired
    private IMtfOrderService orderService;
    @Autowired
    private Jedis jedis;

    public final static String setName = "order";
    public final static String channelName = "channel_order";

    @GetMapping("/createOrder")
    public String createOrder() {
        MtfOrder order1 = new MtfOrder("A001", 12);
        MtfOrder order2 = new MtfOrder("A002", 15);
        MtfOrder order3 = new MtfOrder("A003", 23);
        List<MtfOrder> orderList = Arrays.asList(order1, order2, order3);
        for (MtfOrder order : orderList) {
            redisTemplate.opsForZSet().add(setName,order.getOrderName(),System.currentTimeMillis() + 20*1000);
        }
        return "订单创建成功！";
    }

    @GetMapping("/cancelOrder")
    public String cancelOrder() {
        while (true){
            Set<ZSetOperations.TypedTuple<Object>> elementWithScore = redisTemplate.opsForZSet().rangeWithScores(setName, 0, 0);
            if (ObjectUtil.isEmpty(elementWithScore)){
                log.info("当前延迟队列不存在延时任务！");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                continue;
            }
            Object[] array = elementWithScore.toArray();
            ZSetOperations.TypedTuple<Object> objectTypedTuple = (ZSetOperations.TypedTuple<Object>) array[0];
            Double score = objectTypedTuple.getScore();
            //移除超时的订单
            long currentTimeMillis = System.currentTimeMillis();
            long longValue = score.longValue();
            if (currentTimeMillis > longValue){
                redisTemplate.opsForZSet().removeRange(setName,0,0);
                log.info("订单 {}",objectTypedTuple.getValue()+" 超时，已被移除！");
            }
        }
        //return "ok";
    }

    /**
     * @Description: Redis的发布订阅模式
     * @param
     * @return java.lang.String
     */
    @GetMapping("/publish")
    public String publishMessage() {
        JedisPoolManager.getPool().getResource().publish(channelName,"Hello Redis !");
        return "发布成功！";
    }

    /**
     * @Description: Redis的发布订阅模式
     * @param
     * @return java.lang.String
     */
    @GetMapping("/subscribe")
    public String subscribeMessage() {
        RedisSubscriber redisSubscriber = new RedisSubscriber();
        JedisPoolManager.getPool().getResource().subscribe(redisSubscriber,channelName);
        return "监听结束...";
    }

    @PostMapping("/setList")
    public String setList(@RequestBody List<MtfOrder> orders) {
        log.info("打印集合元素的尺寸：{}",orders.size());
        for (MtfOrder order : orders) {
            System.out.println("订单 "+order.getOrderName()+" 的数量为："+order.getNum());
        }
        orderService.saveBatch(orders);
        return "接口入参可以是集合！";
    }
}
